<?php
/**
 * 数据库连接类
 * 提供数据库连接和基本操作功能
 */

class Database {
    private $connection = null;
    private static $instance = null;
    
    /**
     * 获取数据库实例（单例模式）
     */
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * 构造函数 - 建立数据库连接
     */
    private function __construct() {
        try {
            $config = Config::getDatabaseConfig();
            
            $dsn = "mysql:host={$config['host']};dbname={$config['database']};charset={$config['charset']}";
            $options = [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ];
            
            $this->connection = new PDO($dsn, $config['username'], $config['password'], $options);
        } catch (PDOException $e) {
            throw new Exception("数据库连接失败: " . $e->getMessage());
        }
    }
    
    /**
     * 获取数据库连接
     */
    public function getConnection() {
        return $this->connection;
    }
    
    /**
     * 执行查询并返回所有结果
     */
    public function query($sql, $params = []) {
        try {
            $stmt = $this->connection->prepare($sql);
            $stmt->execute($params);
            return $stmt->fetchAll();
        } catch (PDOException $e) {
            throw new Exception("查询执行失败: " . $e->getMessage());
        }
    }
    
    /**
     * 执行查询并返回单行结果
     */
    public function querySingle($sql, $params = []) {
        try {
            $stmt = $this->connection->prepare($sql);
            $stmt->execute($params);
            return $stmt->fetch();
        } catch (PDOException $e) {
            throw new Exception("查询执行失败: " . $e->getMessage());
        }
    }
    
    /**
     * 执行插入、更新、删除操作
     */
    public function execute($sql, $params = []) {
        try {
            $stmt = $this->connection->prepare($sql);
            $stmt->execute($params);
            return $stmt->rowCount();
        } catch (PDOException $e) {
            throw new Exception("操作执行失败: " . $e->getMessage());
        }
    }
    
    /**
     * 获取最后插入的ID
     */
    public function lastInsertId() {
        return $this->connection->lastInsertId();
    }
    
    /**
     * 开始事务
     */
    public function beginTransaction() {
        return $this->connection->beginTransaction();
    }
    
    /**
     * 提交事务
     */
    public function commit() {
        return $this->connection->commit();
    }
    
    /**
     * 回滚事务
     */
    public function rollback() {
        return $this->connection->rollback();
    }
    
    /**
     * 转义字符串
     */
    public function quote($string) {
        return $this->connection->quote($string);
    }
    
    /**
     * 检查表是否存在
     */
    public function tableExists($tableName) {
        try {
            $sql = "SHOW TABLES LIKE ?";
            $result = $this->query($sql, [$tableName]);
            return count($result) > 0;
        } catch (Exception $e) {
            return false;
        }
    }
    
    /**
     * 关闭数据库连接
     */
    public function close() {
        $this->connection = null;
        self::$instance = null;
    }
}

// 创建全局数据库实例函数
function getDB() {
    return Database::getInstance();
}

// 别名函数，兼容旧代码
function getDatabase() {
    return Database::getInstance();
}

// 获取数据库连接对象
function getDatabaseConnection() {
    return Database::getInstance()->getConnection();
}
?>
